package com.whiteape.book.core.parser;

import com.whiteape.book.core.manager.ParserManager;
import com.whiteape.book.model.bo.CategoryDetailBo;
import com.whiteape.book.model.dto.SiteSourceBean;
import com.whiteape.book.model.dto.SiteSourceCategoryRuleResultBean;
import com.whiteape.book.model.dto.SiteSourceHomepageBean;
import com.whiteape.book.model.dto.SiteSourceHomepageRuleBean;
import com.whiteape.book.utils.URLUtils;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Single;

public class HomepageParser {
    public static Single<List<SiteSourceHomepageBean>> parse(SiteSourceBean siteSourceBean, String currentUrl, String html) {
        List<SiteSourceHomepageBean> resultList = new ArrayList<>();
        if (siteSourceBean == null || StringUtils.isEmpty(html)) {
            return Single.create(emitter -> emitter.onSuccess(resultList));
        }
//        if (siteSourceBean.getHomepage() == null && siteSourceBean.getSiteCategory() == null) {
//            //
//            return Single.create(emitter -> emitter.onSuccess(resultList));
//        }
        return Single.create(emitter -> {

            try {
                //TODO，先不做了,首页用category提取前几个来代替
                SiteSourceHomepageRuleBean homepageRuleBean = new SiteSourceHomepageRuleBean();// = siteSourceBean.getHomepage();
                String listRule = homepageRuleBean.getList();

                //TODO 认定取list的都只有一个？
                List list = ParserManager.getElementList(currentUrl, html, listRule);
                if (list == null || list.size() == 0) {
//                emitter.onError(new Throwable("list not found"));
                    //可能只有一条，直接跳转到书籍详情页面了,在这里做判断

                    //TODO如果直接到详情页的，其实可能同时拿到章节信息，加快下一步点击进入详情的速度
//                boolean parseCatalogTogether = StringUtils.isEmpty(siteSourceBean.getMediaInfoDetailRule().getCatalogUrl());

                    emitter.onSuccess(resultList);
                    return;
                }

                for (Object ele : list) {

                    String doc = ParserManager.getElementString(ele);

                    SiteSourceHomepageBean infoBean = new SiteSourceHomepageBean();
                    HashMap<String, String> varMap = new HashMap<>();
                    infoBean.setVarMap(varMap);

                    String detailRule = homepageRuleBean.getDetailUrl();
                    //TODO text or attr?
                    String detailUrl = ParserManager.parseOne(currentUrl, doc, detailRule, varMap);
                    if (StringUtils.isEmpty(detailUrl)) {
                        continue;
                    }
                    String searchUrl = siteSourceBean.getSearch().getUrl();
                    if (!searchUrl.startsWith("http")) {
                        searchUrl = URLUtils.getAbsolutePath(siteSourceBean.getSiteHostUrl(), searchUrl);
                        siteSourceBean.getSearch().setUrl(searchUrl);
                    }
                    detailUrl = URLUtils.getAbsolutePath(searchUrl, detailUrl);
                    infoBean.setDetailUrl(detailUrl);

                    ///////author
                    String authorRule = homepageRuleBean.getAuthor();
                    String author = ParserManager.parseOne(currentUrl, doc, authorRule, varMap);
                    infoBean.setAuthor(author);

                    ///title
                    String titleRule = homepageRuleBean.getTitle();
                    String title = ParserManager.parseOne(currentUrl, doc, titleRule, varMap);
                    if (StringUtils.isEmpty(title)) {
                        continue;
                    }
                    infoBean.setTitle(title);

                    String coverUrl = ParserManager.parseOne(currentUrl, doc, homepageRuleBean.getCoverUrl(), varMap);
                    if (!coverUrl.isEmpty()) {
                        coverUrl = URLUtils.getAbsolutePath(currentUrl, coverUrl);
                    }
                    infoBean.setCoverUrl(coverUrl);
                    ///.........others
                    infoBean.setMediaType(siteSourceBean.getSiteType());
                    infoBean.setCategory(ParserManager.parseOne(currentUrl, doc, homepageRuleBean.getCategory(), varMap));
                    infoBean.setDesc(ParserManager.parseOne(currentUrl, doc, homepageRuleBean.getDesc(), varMap));
                    infoBean.setLastChapter(ParserManager.parseOne(currentUrl, doc, homepageRuleBean.getLastChapter(), varMap));
                    infoBean.setLastUpdated(ParserManager.parseOne(currentUrl, doc, homepageRuleBean.getLastUpdated(), varMap));
                    infoBean.setState(ParserManager.parseOne(currentUrl, doc, homepageRuleBean.getState(), varMap));
                    infoBean.setWordCount(ParserManager.parseOne(currentUrl, doc, homepageRuleBean.getWordCount(), varMap));



                    //next page : xxxxxxx/{{$page}}/fff
                    //1.根据当前url算出page
                    //2.根据pTotal，算出是否还有next page,填充到page
                    //3.生成新的page url

                    infoBean.setSiteHostUrl(siteSourceBean.getSiteHostUrl());
                    infoBean.setSiteSourceBean(siteSourceBean);

                    resultList.add(infoBean);

                }

                emitter.onSuccess(resultList);
//            emitter.onComplete();
            } catch (Exception e) {
                e.printStackTrace();
                emitter.onSuccess(resultList);
            }

        });

    }

}
